package com.tiamo.chatgpt.common.handle;

import cn.hutool.json.JSONUtil;
import com.tiamo.common.web.controller.BaseController;
import com.tiamo.common.web.exception.BizException;
import com.tiamo.common.web.response.WebResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.HandlerMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述: 全局异常处理类
 */
@Slf4j
@ControllerAdvice({"com.tiamo"})
public class ServiceGlobalExceptionHandler implements BaseController {


    @ResponseStatus(HttpStatus.OK) // 200
    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public WebResponse handleException(Exception ex, WebRequest request) {
        final String exceptionPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE,
                RequestAttributes.SCOPE_REQUEST);
        log.error("系统错误, path:{},params:{}, message:{}", exceptionPath, JSONUtil.toJsonStr(request.getParameterMap()), ex.getMessage(), ex);
        //发送钉钉预警通知
        return createExceptionResponse("操作异常", exceptionPath);
    }

    @ResponseStatus(HttpStatus.OK) // 200
    @ExceptionHandler(value = {BizException.class})
    @ResponseBody
    public WebResponse handleBizException(BizException ex, WebRequest request) {
        final String exceptionPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE,
                RequestAttributes.SCOPE_REQUEST);
        log.warn("业务错误, path:{}, message:{}", exceptionPath, ex.getMessage(), ex);
        return createExceptionResponse(ex.getMessage(), exceptionPath);
    }

    @NotNull
    private WebResponse createExceptionResponse(String errorMessage, String exceptionPath) {
        WebResponse apiResponse = defaultErr(errorMessage);
        List<String> codeGlobalParams = new ArrayList<>();
        codeGlobalParams.add("timestamp:" + System.currentTimeMillis());
        codeGlobalParams.add("path:" + exceptionPath);
        return apiResponse;
    }

}
